//
//  WalkmanPlayerViewController.swift
//  ShimaPlayer
//
//  Created by michael on 2025/7/9.
//

import UIKit

class WalkmanPlayerViewController: UIViewController {
    
    private var currentTime: TimeInterval = 0.0
    private var totalDuration: TimeInterval = 50.0
    private var isUserInteractingWithSlider = false
    private var currentLyricIndex = 0
    private var playbackTimer: Timer?

    // MARK: - UI 组件
    private lazy var backButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(
            UIImage(named: "btn_nav_dismiss")?.withRenderingMode(.alwaysOriginal), for: .normal)
        button.addTarget(self, action: #selector(backButtonTapped), for: .touchUpInside)
        return button
    }()

    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.text = "250307C1新编第2册单词词单"
        label.textColor = UIColor(hexString: "FFFFFF")?.withAlphaComponent(0.66)
        label.font = .systemFont(ofSize: 15, weight: .bold)
        label.textAlignment = .center
        return label
    }()

    private lazy var wordListTableView: UITableView = {
        let tableView = UITableView()
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(WordCell.self, forCellReuseIdentifier: "WordCell")
        return tableView
    }()

    private lazy var progressSlider: CustomSlider = {
        let slider = CustomSlider()
        slider.minimumTrackTintColor = UIColor(hexString: "FFFFFF")
        slider.maximumTrackTintColor = UIColor(hexString: "BABDCA")
        let config = UIImage.SymbolConfiguration(pointSize: 4, weight: .regular)
        slider.setThumbImage(
            UIImage(systemName: "circle.fill", withConfiguration: config)?.withTintColor(
                .white, renderingMode: .alwaysOriginal), for: .normal)
        slider.value = 0.0
        slider.addTarget(self, action: #selector(sliderValueChanged), for: .valueChanged)
        slider.addTarget(self, action: #selector(sliderTouchBegan), for: .touchDown)
        slider.addTarget(
            self, action: #selector(sliderTouchEnded),
            for: [.touchUpInside, .touchUpOutside, .touchCancel])
        return slider
    }()

    private lazy var currentTimeLabel: UILabel = {
        let label = UILabel()
        label.text = "00:00"
        label.textColor = UIColor(hexString: "BABDCA")
        label.font = .systemFont(ofSize: 9)
        return label
    }()

    private lazy var playbackModeLabel: UILabel = {
        let label = UILabel()
        label.text = "自动播放"
        label.textColor = UIColor(hexString: "BABDCA")
        label.font = .systemFont(ofSize: 9)
        label.textAlignment = .center
        return label
    }()

    private lazy var totalTimeLabel: UILabel = {
        let label = UILabel()
        label.text = "00:00"
        label.textColor = UIColor(hexString: "BABDCA")
        label.font = .systemFont(ofSize: 9)
        label.textAlignment = .right
        return label
    }()

    private lazy var repeatButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(
            UIImage(named: "btn_repeat")?.withRenderingMode(.alwaysOriginal), for: .normal)
        button.addTarget(self, action: #selector(playModeButtonTapped), for: .touchUpInside)
        return button
    }()

    private lazy var previousButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(
            UIImage(named: "btn_previous")?.withRenderingMode(.alwaysOriginal), for: .normal)
        button.addTarget(self, action: #selector(previousButtonTapped), for: .touchUpInside)
        return button
    }()

    private lazy var playPauseButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(
            UIImage(named: "btn_pause")?.withRenderingMode(.alwaysOriginal), for: .normal)
        button.addTarget(self, action: #selector(playPauseButtonTapped), for: .touchUpInside)
        return button
    }()

    private lazy var nextButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(
            UIImage(named: "btn_next")?.withRenderingMode(.alwaysOriginal), for: .normal)
        button.addTarget(self, action: #selector(nextButtonTapped), for: .touchUpInside)
        return button
    }()

    private lazy var settingsButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(
            UIImage(named: "btn_settings")?.withRenderingMode(.alwaysOriginal), for: .normal)
        button.addTarget(self, action: #selector(settingsButtonTapped), for: .touchUpInside)
        return button
    }()

    private lazy var favoriteButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(
            UIImage(named: "btn_heart")?.withRenderingMode(.alwaysOriginal), for: .normal)
        button.addTarget(self, action: #selector(favouriteButtonTapped), for: .touchUpInside)
        return button
    }()

    private lazy var listenButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(
            UIImage(named: "btn_listen")?.withRenderingMode(.alwaysOriginal), for: .normal)
        button.addTarget(self, action: #selector(listenButtonTapped), for: .touchUpInside)
        return button
    }()

    // Language display mode enum
    enum LanguageDisplayMode: Int, CaseIterable {
        case both = 0  // 显示日文和中文
        case chineseOnly = 1  // 只显示中文
        case japaneseOnly = 2  // 只显示日文
    }

    // Current language display mode
    private var currentLanguageMode: LanguageDisplayMode = .both {
        didSet {
            updateLanguageSwitchButton()
            // TODO: 这里应该更新单词列表的显示
            wordListTableView.reloadData()
        }
    }

    private lazy var languageSwitchButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("日/中", for: .normal)
        button.titleLabel?.font = .systemFont(ofSize: 10, weight: .medium)
        button.setTitleColor(UIColor(hexString: "BABDCA"), for: .normal)
        button.titleLabel?.font = .systemFont(ofSize: 10, weight: .medium)
        button.layer.borderWidth = 0.7
        button.layer.borderColor = UIColor(hexString: "BABDCA")?.cgColor
        button.layer.cornerRadius = 10
        button.addTarget(self, action: #selector(languageSwitchButtonTapped), for: .touchUpInside)
        return button
    }()

    // 歌词数据结构（带有时间戳）
    private struct LyricLine {
        let text: String
        let startTime: TimeInterval  // 开始时间（秒）
        let endTime: TimeInterval  // 结束时间（秒）
    }

    // 带有时间戳的示例歌词数据
    private let lyrics: [LyricLine] = [
        LyricLine(text: "签证", startTime: 0.0, endTime: 5.0),
        LyricLine(text: "请多多关照", startTime: 5.0, endTime: 10.0),
        LyricLine(text: "猫", startTime: 10.0, endTime: 15.0),
        LyricLine(text: "雪", startTime: 15.0, endTime: 20.0),
        LyricLine(text: "哪儿的话...岂敢岂敢", startTime: 20.0, endTime: 25.0),
        LyricLine(text: "饭店，旅馆", startTime: 25.0, endTime: 30.0),
        LyricLine(text: "快乐、轻松；舒服的", startTime: 30.0, endTime: 35.0),
        LyricLine(text: "钢笔", startTime: 35.0, endTime: 40.0),
        LyricLine(text: "(答应声) 是，是的", startTime: 40.0, endTime: 45.0),
        LyricLine(text: "外出，不在家", startTime: 45.0, endTime: 50.0),
    ]

    private var isLike = false
    private var isRandom = false

    // MARK: - 生命周期
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
//        setupPlayback()
    }

    // MARK: - UI 设置
    private func setupUI() {
        let bgImage = UIImage.gradientImage(colors: [UIColor(hexString: "#1B2340"), UIColor(hexString: "#1C2341"), UIColor(hexString: "#363F65")],
                                            size: view.bounds.size,
                                            startPoint: CGPoint(x: 0.25, y: 0.5),
                                            endPoint: CGPoint(x: 0.75, y: 0.5),
                                            locations: [0, 0.15, 0.46],
                                            transform: CATransform3DMakeAffineTransform(CGAffineTransform(a: 1.2, b: 1.24, c: -1.24, d: 0.25, tx: 0.51, ty: -0.36))
        )
        let bgView = UIImageView(image: bgImage)
        view.addSubview(bgView)
        bgView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        view.addSubview(backButton)
        view.addSubview(titleLabel)

        backButton.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top).offset(10)
            make.leading.equalToSuperview().offset(20)
            make.width.height.equalTo(30)
        }

        titleLabel.snp.makeConstraints { make in
            make.centerY.equalTo(backButton)
            make.centerX.equalToSuperview()
            make.leading.greaterThanOrEqualTo(backButton.snp.trailing).offset(10)
            make.trailing.lessThanOrEqualToSuperview().offset(-20)
        }
        
        let containerView = UIView()
        containerView.backgroundColor = .clear
        view.addSubview(containerView)

        // 添加中心指示线
        //        let centerLineView = UIView()
        //        centerLineView.backgroundColor = UIColor.white.withAlphaComponent(0.2)
        //        centerLineView.layer.cornerRadius = 1
        //        containerView.addSubview(centerLineView)

        containerView.addSubview(wordListTableView)


        wordListTableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

        wordListTableView.tableHeaderView = UIView(
            frame: CGRect(x: 0, y: 0, width: 0, height: containerView.frame.height / 2 - 25))
        wordListTableView.tableFooterView = UIView(
            frame: CGRect(x: 0, y: 0, width: 0, height: containerView.frame.height / 2 - 25))
                
        view.addSubview(progressSlider)
        view.addSubview(currentTimeLabel)
        view.addSubview(playbackModeLabel)
        view.addSubview(totalTimeLabel)

        
        // 初始化时间标签
        updateTimeLabels()

        let controlsStackView = UIStackView(arrangedSubviews: [
            repeatButton, previousButton, playPauseButton, nextButton, settingsButton,
        ])
        controlsStackView.axis = .horizontal
        controlsStackView.distribution = .equalSpacing
        controlsStackView.alignment = .center

        view.addSubview(controlsStackView)
        view.addSubview(languageSwitchButton)
        view.addSubview(favoriteButton)
        view.addSubview(listenButton)
        
        containerView.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(20)
            make.leading.equalToSuperview().offset(20)
            make.trailing.equalToSuperview().offset(-20)
            make.bottom.equalTo(languageSwitchButton.snp.top)
        }

        // 设置中心线的约束
        //        centerLineView.snp.makeConstraints { make in
        //            make.leading.trailing.equalToSuperview().inset(30)
        //            make.height.equalTo(2)
        //            make.center.equalToSuperview()
        //        }

        controlsStackView.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(20)
            make.bottom.equalToSuperview().inset(Size.bottomSafeAreaHeight + 66)
        }

        playPauseButton.snp.makeConstraints { make in
            make.width.height.equalTo(60)
        }

        [repeatButton, previousButton, nextButton, settingsButton].forEach { button in
            button.snp.makeConstraints { make in
                make.width.height.equalTo(30)
            }
        }

        languageSwitchButton.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(20)
            make.bottom.equalTo(progressSlider.snp.top).offset(-40)
            make.width.equalTo(46)
            make.height.equalTo(17)
        }

        listenButton.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-20)
            make.centerY.equalTo(languageSwitchButton)
            make.width.height.equalTo(30)
        }

        favoriteButton.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-64)
            make.centerY.equalTo(languageSwitchButton)
            make.width.height.equalTo(30)
        }

        progressSlider.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(20)
            make.height.equalTo(1)
        }

        currentTimeLabel.snp.makeConstraints { make in
            make.top.equalTo(progressSlider.snp.bottom).offset(10)
            make.leading.equalToSuperview().offset(17)
            make.bottom.equalTo(controlsStackView.snp.top).offset(-40)
        }

        playbackModeLabel.snp.makeConstraints { make in
            make.top.equalTo(progressSlider.snp.bottom).offset(10)
            make.centerX.equalToSuperview()
        }

        totalTimeLabel.snp.makeConstraints { make in
            make.top.equalTo(progressSlider.snp.bottom).offset(10)
            make.trailing.equalTo(progressSlider)
        }
    }
   

    // MARK: - Actions
    @objc private func backButtonTapped() {
        dismiss(animated: true)
    }

    @objc private func languageSwitchButtonTapped() {
        let nextModeRawValue =
            (currentLanguageMode.rawValue + 1) % LanguageDisplayMode.allCases.count
        if let nextMode = LanguageDisplayMode(rawValue: nextModeRawValue) {
            currentLanguageMode = nextMode

        }
    }

    @objc private func playModeButtonTapped() {
        isRandom.toggle()
        repeatButton.setImage(
            UIImage(named: isRandom ? "btn_random" : "btn_repeat")?.withRenderingMode(
                .alwaysOriginal), for: .normal)
    }

    @objc private func favouriteButtonTapped() {
        isLike.toggle()
        favoriteButton.setImage(
            UIImage(named: isLike ? "btn_heart_selected" : "btn_heart")?.withRenderingMode(
                .alwaysOriginal), for: .normal)
    }

    private func updateLanguageSwitchButton() {
        var title: NSAttributedString
        switch currentLanguageMode {
        case .both:
            title = NSMutableAttributedString(string: "日/中")
        case .chineseOnly:
            title = NSMutableAttributedString(string: "日/中").setColor(
                for: "日/", color: UIColor(hexString: "FFFFFF")?.withAlphaComponent(0.2) ?? .white)
        case .japaneseOnly:
            title = NSMutableAttributedString(string: "日/中").setColor(
                for: "/中", color: UIColor(hexString: "FFFFFF")?.withAlphaComponent(0.2) ?? .white)
        }
        languageSwitchButton.setAttributedTitle(title, for: .normal)
    }

    @objc private func settingsButtonTapped() {
        let bottomSheet = PlaySettingBottomSheet()
        let popup = PopupView(contentView: bottomSheet, style: .bottomSheet(height: 490))
        popup.show(in: self)
        bottomSheet.configureActions(onPlaySettingChangedAction: nil)
    }

    @objc private func previousButtonTapped() {
//        showTooltip(with: "点击上一首")
    }

    @objc private func nextButtonTapped() {
//        showTooltip(with: "点击下一首")
    }

    @objc private func listenButtonTapped() {
        let dataSource = [
            WhiteNoiseItem(name: "白噪音", isSelected: true),
            WhiteNoiseItem(name: "雨声", isSelected: false),
            WhiteNoiseItem(name: "海浪声", isSelected: false),
            WhiteNoiseItem(name: "森林声", isSelected: false),
            WhiteNoiseItem(name: "鸟鸣声", isSelected: false),
            WhiteNoiseItem(name: "蝉鸣声", isSelected: false),
            WhiteNoiseItem(name: "钟声", isSelected: false),
            WhiteNoiseItem(name: "钟声", isSelected: false),
        ]
        let bottomSheet = WhiteNoiseBottomSheet()
        bottomSheet.dataSource = dataSource
        let popup = PopupView(contentView: bottomSheet, style: .bottomSheet(height: 490))
        popup.show(in: self)
    }
}

// MARK: - UITableViewDelegate & UITableViewDataSource
extension WalkmanPlayerViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return lyrics.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell =
            tableView.dequeueReusableCell(withIdentifier: "WordCell", for: indexPath) as! WordCell

        // 计算与当前索引的距离，用于渐变效果
        let distanceFromCurrent = abs(indexPath.row - currentLyricIndex)

        // 确定这是否是过去的歌词（在当前歌词之前）
        let isPastLyric = indexPath.row < currentLyricIndex

        // 使用文本和渐变效果配置单元格
        cell.configure(
            with: lyrics[indexPath.row].text,
            isHighlighted: indexPath.row == currentLyricIndex,
            distanceFromCurrent: distanceFromCurrent,
            isPastLyric: isPastLyric
        )

        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50
    }
}

// MARK: - WordCell
class WordCell: UITableViewCell {
    private let wordLabel: UILabel = {
        let label = UILabel()
        label.textColor = .white
        label.font = .systemFont(ofSize: 16)
        label.textAlignment = .center
        return label
    }()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupCell()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupCell() {
        backgroundColor = .clear
        selectionStyle = .none

        contentView.addSubview(wordLabel)
        wordLabel.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }

    func configure(
        with word: String, isHighlighted: Bool = false, distanceFromCurrent: Int = 0,
        isPastLyric: Bool = false
    ) {
        wordLabel.text = word

        // 渐变效果考虑的最大距离
        let maxDistance = 5

        // 根据与当前歌词的距离应用渐变效果
        if isHighlighted {
            // 当前歌词 - 蓝色，不透明度为 100%
            wordLabel.textColor = UIColor(hexString: "FFFFFF")
            wordLabel.font = .systemFont(ofSize: 17, weight: .medium)
        } else {
            // 根据距离计算透明度（越近 = 越可见）
            let alpha = max(1.0 - (Double(distanceFromCurrent) / Double(maxDistance)), 0.3)

            // 为过去的歌词应用额外的淡出效果
            if isPastLyric {
                // 过去的歌词有不同的颜色和降低的不透明度
                let pastLyricAlpha = max(alpha * 0.7, 0.3)  // 比未来歌词更透明
                //                wordLabel.textColor = UIColor(red: 0.6, green: 0.6, blue: 0.8, alpha: CGFloat(pastLyricAlpha))
                wordLabel.textColor = UIColor(hexString: "FFFFFF")?.withAlphaComponent(
                    CGFloat(pastLyricAlpha))
            } else {
                // 未来歌词保持白色，透明度根据计算结果
                wordLabel.textColor = UIColor(hexString: "FFFFFF")?.withAlphaComponent(
                    CGFloat(alpha))
            }

            wordLabel.font = .systemFont(ofSize: 15, weight: .medium)
        }
    }
}

// MARK: - Playback Control Extension
extension WalkmanPlayerViewController {
    // MARK: - 播放控制

    private func setupPlayback() {
        // 初始化播放定时器
        startPlaybackTimer()

        // 更新 UI 以反映初始状态
        updateTimeLabels()
        updateProgressSlider()
    }

    private func startPlaybackTimer() {
        // 取消现有的定时器（如果有）
        playbackTimer?.invalidate()

        // 创建一个每 0.1 秒触发一次的新定时器
        playbackTimer = Timer.scheduledTimer(
            timeInterval: 0.1, target: self, selector: #selector(updatePlayback), userInfo: nil,
            repeats: true)
    }

    @objc private func updatePlayback() {
        // 跳过用户与滑块交互时的更新
        if isUserInteractingWithSlider {
            return
        }

        // 更新当前时间（模拟播放）
        currentTime += 0.1
        if currentTime > totalDuration {
            currentTime = 0.0
        }

        // 更新 UI
        updateTimeLabels()
        updateProgressSlider()
        updateCurrentLyric()
    }

    private func updateTimeLabels() {
        // 计算和格式化进度百分比
        let progressPercentage = Int((currentTime / totalDuration) * 100)
        currentTimeLabel.text = String(format: "%d%%", progressPercentage)

        // 显示当前歌词索引和总歌词数
        totalTimeLabel.text = String(format: "%d/%d", currentLyricIndex + 1, lyrics.count)
    }

    private func updateProgressSlider() {
        // 根据当前时间更新滑块值
        progressSlider.value = Float(currentTime / totalDuration)
    }

    private func updateCurrentLyric() {
        // 根据当前时间查找当前歌词
        var newLyricIndex = 0
        for (index, lyric) in lyrics.enumerated() {
            if currentTime >= lyric.startTime && currentTime < lyric.endTime {
                newLyricIndex = index
                break
            }
        }

        // 如果歌词索引发生变化，更新 UI
        if newLyricIndex != currentLyricIndex {
            let oldIndex = currentLyricIndex
            currentLyricIndex = newLyricIndex

            // 更新单元格
            wordListTableView.reloadRows(
                at: [
                    IndexPath(row: oldIndex, section: 0), IndexPath(row: newLyricIndex, section: 0),
                ], with: .none)

            // 滚动到当前歌词
            scrollToCurrentLyric(animated: true)
        }
    }

    private func scrollToCurrentLyric(animated: Bool) {
        if currentLyricIndex < lyrics.count {
            wordListTableView.scrollToRow(
                at: IndexPath(row: currentLyricIndex, section: 0), at: .middle, animated: animated)
        }
    }

    // 视图布局完成后更新头部和尾部高度
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        // 确保头部和尾部大小正确，以便居中
        let cellHeight: CGFloat = 50  // 来自 tableView 代理的单元格高度
        let visibleHeight = wordListTableView.bounds.height
        let headerFooterHeight = (visibleHeight - cellHeight) / 2

        if wordListTableView.tableHeaderView?.frame.height != headerFooterHeight {
            wordListTableView.tableHeaderView = UIView(
                frame: CGRect(
                    x: 0, y: 0, width: wordListTableView.bounds.width, height: headerFooterHeight))
            wordListTableView.tableFooterView = UIView(
                frame: CGRect(
                    x: 0, y: 0, width: wordListTableView.bounds.width, height: headerFooterHeight))

            // 更新头部/尾部后重新滚动到当前歌词
            if currentLyricIndex < lyrics.count {
                wordListTableView.scrollToRow(
                    at: IndexPath(row: currentLyricIndex, section: 0), at: .middle, animated: false)
            }
        }
    }

    // MARK: - 用户交互处理

    @objc private func sliderValueChanged() {
        // 根据滑块值计算新时间
        let newTime = Double(progressSlider.value) * totalDuration

        // Update current time
        currentTime = newTime

        // Update UI
        updateTimeLabels()
        updateCurrentLyric()
    }

    @objc private func sliderTouchBegan() {
        // 设置标志以防止用户交互时的定时器更新
        isUserInteractingWithSlider = true
    }

    @objc private func sliderTouchEnded() {
        // 清除标志以恢复定时器更新
        isUserInteractingWithSlider = false
    }

    @objc private func playPauseButtonTapped() {
        // 切换播放状态
        if playbackTimer?.isValid == true {
            // 暂停播放
            playbackTimer?.invalidate()
            playPauseButton.setImage(
                UIImage(named: "btn_play")?.withRenderingMode(.alwaysOriginal), for: .normal)
        } else {
            // 恢复播放
            startPlaybackTimer()
            playPauseButton.setImage(
                UIImage(named: "btn_pause")?.withRenderingMode(.alwaysOriginal), for: .normal)
        }
    }

    // MARK: - TableView 交互

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        // 更新当前歌词索引
        currentLyricIndex = indexPath.row

        // 根据选定的歌词更新当前时间
        currentTime = lyrics[indexPath.row].startTime

        // Update UI
        updateTimeLabels()
        updateProgressSlider()
        wordListTableView.reloadData()
    }
}

class CustomSlider: UISlider {

    var sliderHeight: CGFloat = 1
    
    init(sliderHeight: CGFloat = 1) {
        self.sliderHeight = sliderHeight
        super.init(frame: .zero)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func minimumValueImageRect(forBounds bounds: CGRect) -> CGRect {
        return self.bounds
    }

    override func maximumValueImageRect(forBounds bounds: CGRect) -> CGRect {
        return self.bounds
    }

    override func trackRect(forBounds bounds: CGRect) -> CGRect {
        let rect = super.trackRect(forBounds: bounds)
        layer.cornerRadius = sliderHeight / 2
        return CGRect.init(
            x: rect.origin.x, y: (bounds.size.height - sliderHeight) / 2, width: bounds.size.width,
            height: sliderHeight)
    }

    override func thumbRect(forBounds bounds: CGRect, trackRect rect: CGRect, value: Float)
        -> CGRect
    {
        return super.thumbRect(forBounds: bounds, trackRect: rect, value: value)
    }

}


class WhiteNoiseBottomSheet: UIView, UITableViewDataSource, UITableViewDelegate {

    var onSwitchChanged: ((Bool) -> Void)?
    var onSelectedIndexChanged: ((Int) -> Void)?
    var dataSource: [WhiteNoiseItem] = [] {
        didSet {
            tableView.reloadData()
        }
    }

    private let tableView: UITableView = {
        let tableView = UITableView()
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.rowHeight = 113
        tableView.sectionFooterHeight = 20
        return tableView
    }()

    init() {
        super.init(frame: .zero)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func configureActions(onSwitchChangedAction: ((Bool) -> Void)?, onSelectedIndexChangedAction: ((Int) -> Void)?) {
        onSwitchChanged = onSwitchChangedAction
        onSelectedIndexChanged = onSelectedIndexChangedAction
    }
    
    private func setupUI() {
        backgroundColor = UIColor(hexString: "FFFFFF")
        layer.cornerRadius = 25
        
        let indicatorView = UIView()
        indicatorView.backgroundColor = UIColor(hexString: "#C9CEDA")
        indicatorView.layer.cornerRadius = 1.5

        addSubview(indicatorView)
        indicatorView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(9)
            make.centerX.equalToSuperview()
            make.height.equalTo(3)
            make.width.equalTo(26)
        }
        
        let titleLabel = UILabel()
        titleLabel.text = "背景白噪音"
        titleLabel.textColor = UIColor(hexString: "#1C1F1E")
        titleLabel.font = .systemFont(ofSize: 17, weight: .bold)
        titleLabel.textAlignment = .center

        let switchButton = UISwitch()
        switchButton.addTarget(self, action: #selector(switchButtonTapped), for: .valueChanged)
        
        let stackView = UIStackView(arrangedSubviews: [titleLabel, switchButton])
        stackView.axis = .horizontal
        stackView.alignment = .center
        stackView.spacing = 11
        
        addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.top.equalTo(indicatorView.snp.bottom).offset(6)
            make.centerX.equalToSuperview()
        }
        
        tableView.dataSource = self
        tableView.delegate = self
        
        addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(stackView.snp.bottom).offset(20)
            make.horizontalEdges.equalToSuperview()
            make.bottom.equalToSuperview().inset(Size.bottomSafeAreaHeight)
            make.height.lessThanOrEqualTo((tableView.rowHeight + tableView.sectionFooterHeight) * 3)
        }
        
    }
    
    @objc private func switchButtonTapped(_ sender: UISwitch) {
        onSwitchChanged?(sender.isOn)
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        dataSource.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        1
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        UIView()
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: WhiteNoiseCell = WhiteNoiseCell.cell(withTableView: tableView)
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        onSelectedIndexChanged?(indexPath.row)
    }
}

class WhiteNoiseCell: UITableViewCell {
    
    private let bgView: UIImageView = {
        let view = UIImageView()
        view.backgroundColor = .red
        view.layer.cornerRadius = 25
        view.layer.masksToBounds = true
        return view
    }()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupCell()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupCell() {
        backgroundColor = UIColor(hexString: "FFFFFF")
        selectionStyle = .none

        contentView.addSubview(bgView)
        bgView.snp.makeConstraints { make in
            make.top.bottom.equalToSuperview()
            make.horizontalEdges.equalToSuperview().inset(16)
        }
    }
    
}

struct WhiteNoiseItem {
    let name: String
    var isSelected: Bool
}


// 播放设置bottomsheet
class PlaySettingBottomSheet: UIView {

    var onPlaySettingChanged: ((PlaySetting) -> Void)?
    var playSetting: PlaySetting = PlaySetting.defaultSetting()

    private let repeatList: [Int] = [1, 2, 3, 4, 5]
    private let intervalList: [TimeInterval] = [0.5, 1, 3, 5, 8]
    private let speedList: [Float] = [0.5, 0.75, 1, 1.25, 1.5]
    private let durationList: [Int] = [15, 25, 45, 60, 75]

    init() {
        super.init(frame: .zero)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        backgroundColor = UIColor(hexString: "FFFFFF")
        layer.cornerRadius = 25
        
        let indicatorView = UIView()
        indicatorView.backgroundColor = UIColor(hexString: "#C9CEDA")
        indicatorView.layer.cornerRadius = 1.5

        addSubview(indicatorView)
        indicatorView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(9)
            make.centerX.equalToSuperview()
            make.height.equalTo(3)
            make.width.equalTo(26)
        }
        
        let titleLabel = UILabel()
        titleLabel.text = "播放设置"
        titleLabel.textColor = UIColor(hexString: "#1C1F1E")
        titleLabel.font = .systemFont(ofSize: 17, weight: .bold)
        titleLabel.textAlignment = .center
        
        addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(indicatorView.snp.bottom).offset(6)
            make.centerX.equalToSuperview()
        }

        let repeatCountView = createOptionSelector(title: "重复次数",
                                                   options: repeatList,
                                                   unit: "次",
                                                   selectedOption: playSetting.repeatCount,
                                                   onSelectedValueChange: { [weak self] value in
            self?.playSetting.repeatCount = value
            print("repeatCount: \(value)")
        })
        let playIntervalView = createOptionSelector(title: "播放间隔", options: intervalList, unit: "s", selectedOption: playSetting.playInterval, onSelectedValueChange: { [weak self] value in
            self?.playSetting.playInterval = value
            print("playInterval: \(value)")
        })
       let playSpeedView = createOptionSelector(title: "播放倍速", options: speedList, unit: "x", selectedOption: playSetting.playSpeed, onSelectedValueChange: { [weak self] value in
            self?.playSetting.playSpeed = value
            print("playSpeed: \(value)")
        })

        let playAudioView = PlaySettingSwitchOptionSelector(title: "释义音频", switchOn: playSetting.playAudio, onSwitchChangedAction: { [weak self] value in
            self?.playSetting.playAudio = value
            print("playAudio: \(value)")
        })
        let autoPlayNextWordView = PlaySettingSwitchOptionSelector(title: "自动播放下一词", switchOn: playSetting.autoPlayNextWord, onSwitchChangedAction: { [weak self] value in
            self?.playSetting.autoPlayNextWord = value
            print("autoPlayNextWord: \(value)")
        })
        let autoCloseView = PlaySettingSwitchOptionSelector(title: "定时关闭", switchOn: playSetting.autoClose, onSwitchChangedAction: { [weak self] value in
            self?.playSetting.autoClose = value
            print("autoClose: \(value)")
        })
        let autoCloseTimeView = createOptionSelector(title: "定时关闭时间", options: durationList, unit: "min", selectedOption: playSetting.autoCloseTime, onSelectedValueChange: { [weak self] value in
            self?.playSetting.autoCloseTime = value
            print("autoCloseTime: \(value)")
        })
        // let customDurationView = createOptionSelector(title: "自定义时长", options: durationList, unit: "min", selectedOption: playSetting.customDuration, onSelectedValueChange: { [weak self] value in
        //     self?.playSetting.customDuration = value
        //     print("customDuration: \(value)")
        // })

        let stackView = UIStackView(arrangedSubviews: [repeatCountView, playIntervalView, playSpeedView, playAudioView, autoPlayNextWordView, autoCloseView, autoCloseTimeView])
        stackView.axis = .vertical
        stackView.alignment = .leading
        stackView.spacing = 20
        stackView.distribution = .equalSpacing

        addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(20)
            make.horizontalEdges.equalToSuperview().inset(16)
            make.bottom.equalToSuperview().inset(20)
        }

    }

    func configureActions(onPlaySettingChangedAction: ((PlaySetting) -> Void)?) {
        onPlaySettingChanged = onPlaySettingChangedAction
    }
    

    // 使用新的PlaySettingOptionSelector替代原来的selectView方法
    private func createOptionSelector<T: Equatable>(title: String, options: [T], unit: String, selectedOption: T, onSelectedValueChange: ((T) -> Void)?) -> PlaySettingOptionSelector<T> {
        let selector = PlaySettingOptionSelector(title: title, options: options, unit: unit, selectedOption: selectedOption)
        selector.onSelectedOptionChanged = onSelectedValueChange
        return selector
    }

    private func switchItemView(onSwitchChanged: ((Bool) -> Void)?) -> UIView {
        let switchItemView = UIView()
//        switchItemView.onSwitchChanged = { [weak self] isOn in
//            self?.playSetting.playAudio = isOn
//        }
        return switchItemView
    }
    
    @objc private func optionButtonTapped(_ sender: UIButton) {
        
    }
    
}


struct PlaySetting {
    // 播放模式
    var playMode: PlayMode
    // 复读次数
    var repeatCount: Int
    // 播放间隔
    var playInterval: TimeInterval
    // 播放倍速
    var playSpeed: Float
    // 释义音频
    var playAudio: Bool
    // 自动播放下一词开关
    var autoPlayNextWord: Bool
    // 定时关闭开关
    var autoClose: Bool
    // 定时关闭时间(分钟)
    var autoCloseTime: Int
    // 自定义时长(分钟)
    var customDuration: Int

    static func defaultSetting() -> PlaySetting {
        return PlaySetting(playMode: .repeatMode, repeatCount: 1, playInterval: 1, playSpeed: 1, playAudio: true, autoPlayNextWord: true, autoClose: true, autoCloseTime: 1, customDuration: 1)
    }
}

enum PlayMode {
    case repeatMode
    case custom
}
    
    
